using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ShopForWeb.Api.Utils.Filters;
using ShopForWeb.Dtos.Profiles;
using ShopForWeb.Models.DbContexts;
using ShopForWeb.Services;

var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;

// Add services to the container.
#region 数据库上下文
services.AddDbContextPool<ShopDbContext>(options =>
{
  options.UseSqlServer(configuration.GetConnectionString("ShopDB"), b => b.MigrationsAssembly("ShopForWeb.Api"))
         .UseLazyLoadingProxies();  //启用延迟加载        
});
#endregion
// Add services to the container.
services.AddScoped<ProductServices>();
services.AddScoped<ShoppingCartServices>();
services.AddScoped<OrderServices>();
services.AddScoped<UserServices>();
services.AddAutoMapper(typeof(ShopProfile));

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.
AddControllersWithViews(options => options.Filters.Add<GlobalExceptionFilter>())
.AddNewtonsoftJson(options =>
{
  //修改属性名称的序列化方式，首字母小写，即驼峰样式，默认
  options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  //解决命名不一致问题 ，与服务器一致，和上面的二选一
  //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
  //忽略循环引用
  options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  //空值处理
  options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
  app.UseSwagger();
  app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthorization();
app.MapControllers();
app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
  public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
